<?php
/**
 * Class:   Router
 * About:   Маршрутизатор системы
 * Author:  Vlad Andreev <php.vlad@gmail.com>
 **/

namespace Router;

class Router extends \Control\Model {
    
    public $route        = '';
    public $controllers  = array();
    public $actions      = array();
    
    public function __construct() {
        
        parent::__construct();
        
        $this->repository = $this->em->getRepository('Router\Entities\Route');
    }
    
    public function findByRequest($request) {
        
        $result = null;
        
        // Если маршрут пустой или содержит только один пустой элемент,
        // ищем маршрут "/home"
        $this->_request = (!empty($request) && !($request[0] == '' && count($request) == 1))
            ? $request
            : array(0 => 'home')
        ;
        
        $ancestors = $this->getAncestors();
        $count = count($ancestors);
        $i = 0;
        
        while (empty($route) && $i < $count) {
            $route = $this->repository->findOneBy(array('route' => $ancestors[$i], 'active' => 1));
            
            if (!empty($route))
                $result = $route;
            
            $i++;
        }
        
        return $result;
    }
    
    private function getAncestors() {
        
        $ancestors = array();
        
        $path   = $this->_request;
        $length = count($path);
        
        for ($l=$length; $l>0; $l--) {
            $mask = pow(2, $l);
            
            for ($i=0; $i<$mask; $i++) {
                $ancestor = array();
                $m = base_convert($i, 10, 2);
                
                while (strlen($m) < $l)
                    $m = '0'. $m;
                
                for ($j=0; $j<$l; $j++) {
                    if (empty($m{$j}) && isset($path[$j]))
                        $ancestor[] = $path[$j];
                    else
                        $ancestor[] = '%';
                }
                
                $ancestors[] = implode('/', $ancestor);
            }
        }
        
        return $ancestors;
    }
    
    // Сохранить
    public function save($data, $id = null) {
        
        if(!empty($id))
            $item = $this->find($id);
        
        if(empty($item))
            $item = new \Router\Entities\Route;
        
        $entityFields = array_keys(get_object_vars($item));
        
        foreach($data as $field => $value)
            if (in_array($field, $entityFields))
                $item->$field = $value;
        
        $this->em->persist($item);
        $this->em->flush();
        
        return $item->id;
    }
}